package com.faithnmn.radio.service;

import java.io.IOException;

import com.faithnmn.radio.MainActivity;
import com.faithnmn.radio.common.Constants;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.os.PowerManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class RadioOnlineService extends Service {

	private MediaPlayer player;
	private boolean isPausedByRinging = false;
	private TelephonyManager tm;
	public static PowerManager.WakeLock wl;
	public static NotificationManager mNotificationManager;
	public static boolean isPlaying = false;
	public static boolean forceStop = false;
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(intent != null && intent.getAction()!= null){
			if(intent.getAction().equals(Constants.START_RADIO_ACTION)){
				forceStop = false;
				if(player!=null && !player.isPlaying()){
					player.start();
					isPlaying = true;
				}else if(player == null){
					initializeMediaPlayer();
				}
			}else if(intent.getAction().equals(Constants.STOP_RADIO_ACTION)){
				forceStop = true;
				if(player!=null && player.isPlaying()){
					player.pause();
					isPlaying = false;
				}else{
					Log.e("RadioService", "Radio already stopped!");
				}
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	public void streamErrorHandler() {

		Toast t = Toast.makeText(this, "Network error..",Toast.LENGTH_LONG);
		t.setGravity(Gravity.TOP | Gravity.CENTER, 0, 100);
		t.show();
		if(MainActivity.playPause != null){
			MainActivity.playPause.setText("PLay Radio");
		}
		isPlaying = false;
		player.stop();
		player.release();
		player = null;
	}
	
	@Override
	public void onDestroy() {
		player.stop();
		player.release();
		player = null;
//		mNotificationManager.cancel(RADIO_NOTIFICATION_ID);
		if (wl.isHeld()) {
			// kill the wake lock
			wl.release();
			wl = null;
		}
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	private void initializeMediaPlayer() {
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            player.setDataSource("http://shoutmedia.abc.net.au:10424");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            streamErrorHandler();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            streamErrorHandler();
        } catch (IOException e) {
            e.printStackTrace();
            streamErrorHandler();
        }
        player.setOnErrorListener(new OnErrorListener() {
			
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				streamErrorHandler();
				return false;
			}
		});
        player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
//                playSeekBar.setSecondaryProgress(percent);
                Log.e("Buffering", "" + percent);
                if(forceStop){
                	player.stop();
                	player.release();
                	player = null;
                	MainActivity.status.setText("");
                	return;
                }
                if(MainActivity.status != null){
                	MainActivity.status.setText("Bufferring.."+percent);
                }
            }
        });
        try {
			player.prepareAsync();;
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
			streamErrorHandler();
		}
        player.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {
            	player.start();
            	isPlaying = true;
            	tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
				tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
				PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
				wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,"radioStream");
				wl.acquire();
            }
        });
    }
	
	private PhoneStateListener mPhoneListener = new PhoneStateListener() {
		public void onCallStateChanged(int state, String incomingNumber) {
			try {
				switch (state) {
				case TelephonyManager.CALL_STATE_RINGING:
					player.pause();
					isPlaying = false;
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					player.start();
					isPlaying = true;
					break;
				case TelephonyManager.CALL_STATE_IDLE:
					break;
				default:
				}
			} catch (Exception e) {
			}
		}
	};
	
}
